export class AsyncAction {
  pending = false
  work: any
  state: any
  delay: number = 0
  id: any
  constructor(work: Function) {
    this.work = work
  }
  schedule(state: any, delay: number = 0) {
    this.state = state
    this.delay = delay
    // 避免定时器重复创建
    if (this.id !== null) {
      this.id = this.recycleAsyncId(this.id)
    }
    this.pending = true
    // 调用函数获取定时器Id
    // 当前schedule状态为开启才能调用定时器执行work
    this.id = this.requestAsyncId(delay)
    return this
  }
  requestAsyncId(delay: number) {
    return setInterval(this.execute.bind(this), delay)
  }
  recycleAsyncId(id: number) {
    if (this.id !== null) {
      clearInterval(id)
    }
    return null
  }
  execute() {
    // 如果再次调用schedule
    this.pending = false
    // 在work中如果再次调用schedule pending 就会发生变化。断定为调用新任务
    this.work(this.state)
    // 如果在work中没有调度新的任务的话，清除定时器
    if (this.pending === false && this.id !== null) {
      this.id = this.recycleAsyncId(this.id)
    }
  }
}